
use std::error::Error;
use std::io::{Write, Read};
use std::net::{TcpListener, TcpStream};
use icc_server::{IccParam, icc_deal::icc_rsp};

pub fn handle_client(param: &IccParam) -> Result<(), Box<dyn Error>> 
{
    // 监听指定的 IP 和端口
    let addr = format!("{}:{}", param.ip, param.up_port);
    println!("Server listening on {}", addr);
    let listener = TcpListener::bind(&addr)?;

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                println!("new {} connection to {}", stream.peer_addr().unwrap(), addr);
                connect_deal(stream);
            }
            Err(e) => {
                eprintln!("Error on {}: {}", addr, e);
            }
        }
    }
    Ok(())
}

fn connect_deal(mut stream: TcpStream)
{
    // 读取客户端发送的数据
    let mut buffer = [0; 4096];
    let mut process: u8 = 0;

    loop {
        buffer.fill(0); //接收前清空
        let result = stream.read(&mut buffer);
        let rcv_len = match result {
            Ok(n) => {
                if n == 0 {
                    println!("Client disconnected");
                    return;
                }
                n
            }
            Err(e) => {
                eprintln!("Error reading from stream: {}", e);
                return;
            }
        };

        // 处理客户端发送的数据
        println!("up rcv: {}", String::from_utf8_lossy(&buffer[..rcv_len]));

        let json_str = std::str::from_utf8(&buffer[..rcv_len]).unwrap_or_else(|err| {
            eprintln!("Error converting buffer to UTF-8, err inof:{}", err);
            return "";
        });
        let json_value: serde_json::Value = serde_json::from_str(json_str).unwrap_or_else(|err| {
            eprintln!("Error parsing JSON, err info:{}", err);
            return serde_json::Value::Null;
        });

        buffer.fill(0); //发送前清空
        let event = json_value["event"].as_u64().unwrap() as u32;
        let len = match event {
            208|201|203|206|207|211|212 => {    //201车机包下载请求
                let data = icc_rsp::universal(event);
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
            202 => {    //下载进度请求
                let mut result: u8 = 1; //下载中
                if process < 100 {
                    process += 10;
                } else {
                    result = 2; //下载完成
                }
                    
                let data = icc_rsp::event202(process, 0, result, 0);
                process = 0;
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
            204 => {    //升级进度结果请求
                let mut result: u8 = 1; //升级中
                if process < 100 {
                    process += 10;
                } else {
                    result = 2; //升级成功
                }
                let data = icc_rsp::event204(process, 0, 0, result, 0);
                process = 0;
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
            210 => {
                let data = icc_rsp::event210(1);
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()                
            }
            _ => {
                let data = "Not yet supported...".to_string();
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
        };

        // 发送响应数据
        stream.write_all(&buffer[..len]).unwrap_or_else(|err| {
            eprintln!("Error writing to stream: {}", err);
        });
        println!("up send: {}", String::from_utf8_lossy(&buffer[..len]));
    }
}